/**
 * Created by tangzk on 2016/7/1.
 */

;(function ($) {

    var currentHeight,
        $sly,
        $menuFrame = $('#menuFrame'),
        $menuWrap = $menuFrame.parent();

    var beforeUIReady = function () {
        globalVars.$body = $('body');
        globalVars.$frameContainer = $('#frameContainer');
        globalVars.$sidebarMenu = globalVars.$frameContainer.find('.sidebar-menu');
        globalVars.$mainMenu = $('#mainMenu');
        globalVars.$mainContent = globalVars.$frameContainer.find('.main-content');
        globalVars.$topNav = $('#topNav');
        globalVars.$frameView = $('#frameView');
        globalVars.breakpoints = {
            largescreen: [991, -1],
            tabletscreen: [768, 990],
            devicescreen: [420, 767],
            sdevicescreen: [0, 419]
        };
        setupSidebarMenu();
    };

    var UIReady = function () {
        globalVars.$loading.hide();
        globalVars.$frameContainer.show();
    };

    var renderFrameLayout = function () {
        var conHt = globalVars.$window.height(),
            topNavHt = globalVars.$topNav.height(),
            frmHt = conHt - topNavHt;
        globalVars.$frameContainer.height(conHt);
        globalVars.$sidebarMenu.height(conHt);
        globalVars.$mainContent.height(conHt);
        globalVars.$frameView.height(frmHt);
    };

    // Get current breakpoint
    function getCurrentBreakpoint() {
        var width = jQuery(window).width(),
            breakpoints = globalVars.breakpoints;
        for (var breakpontLabel in breakpoints) {
            var bpArr = breakpoints[breakpontLabel],
                min = bpArr[0],
                max = bpArr[1];
            if (max == -1)
                max = width;
            if (min <= width && max >= width) {
                return breakpontLabel;
            }
        }
        return null;
    }

    // Check current screen breakpoint
    function is(screenLabel) {
        return getCurrentBreakpoint() == screenLabel;
    }

    // Is xs device
    function isxs() {
        return is('devicescreen') || is('sdevicescreen');
    }

    // Sidebar Menu Setup
    function setupSidebarMenu() {
        var $itemsWithSubmenu = globalVars.$sidebarMenu.find('li:has(ul)'),
            submenuOptions = {
                submenuOpenDelay: 0.5,
                submenuOpenEasing: Sine.easeInOut,
                submenuOpenedClass: 'opened'
            },
            rootLevelClass = 'root-level',
            isMultiopen = globalVars.$mainMenu.hasClass('multiple-expanded');

        globalVars.$mainMenu.find('> li').addClass(rootLevelClass);

        $itemsWithSubmenu.each(function (i, el) {
            var $this = $(el),
                $link = $this.find('> a'),
                $submenu = $this.find('> ul');

            $this.addClass('has-sub');
            $link.click(function (ev) {
                ev.preventDefault();

                if (!isMultiopen && $this.hasClass(rootLevelClass)) {
                    var closeSubmenus = globalVars.$mainMenu.find('.' + rootLevelClass).not($this).find('> ul');

                    closeSubmenus.each(function (i, el) {
                        var $sub = $(el);
                        menuDoCollapse($sub, $sub.parent(), submenuOptions);
                    });
                }

                if (!$this.hasClass(submenuOptions.submenuOpenedClass)) {
                    if (!$submenu.is(':visible')) {
                        menuDoExpand($submenu, $this, submenuOptions);
                    }
                }
                else {
                    menuDoCollapse($submenu, $this, submenuOptions);
                }
            });
        });

        // Open the submenus with "opened" class
        globalVars.$mainMenu.find('.' + submenuOptions.submenuOpenedClass + ' > ul').addClass('visible');

        // Well, somebody may forgot to add "active" for all inhertiance, but we are going to help you (just in case) - we do this job for you for free :P!
        if (globalVars.$mainMenu.hasClass('auto-inherit-active-class')) {
            menuSetActiveClassToParents(globalVars.$mainMenu.find('.active'));
        }
        // Collapse Icon (mobile device visible)
        var showHideMenu = $('');
        globalVars.$sidebarMenu.find('.logo-env').append(showHideMenu);

        slyRender();
    }

    function slyRender() {
        if ($sly) {
            $sly.reload();
        }
        else {
            var $scrollbar = $menuWrap.find('.scrollbar');
            // 优化滚动条
            $sly = new Sly(
                '#menuFrame',
                {
                    speed: 300,
                    scrollBy: 100,
                    scrollBar: $scrollbar,
                    dragHandle: 1,
                    dynamicHandle: 1,
                    clickBar: 1
                },
                {
                    load: function () {
                        // 如果窗体高度大于菜单长度，则隐藏滚动条
                        if ($menuFrame.height() >= $menuFrame.find('.slidee').height()) {
                            $scrollbar.hide();
                        }
                        else {
                            $scrollbar.show();
                        }
                    }
                }
            );
            $sly.init();
        }
    }

    function menuSetActiveClassToParents($activeElement) {
        if ($activeElement.length) {
            var $parent = $activeElement.parent().parent();
            $parent.addClass('active');
            if (!$parent.hasClass('root-level')) {
                menuSetActiveClassToParents($parent);
            }
        }
    }

    function menuDoCollapse($submenu, $this, options) {
        if (globalVars.$frameContainer.hasClass('sidebar-collapsed') && $this.hasClass('root-level')) {
            return;
        }
        $this.removeClass(options.submenuOpenedClass);
        TweenMax.to($submenu, options.submenuOpenDelay, {
            css: {height: 0, opacity: .2}, ease: options.submenuOpenEasing, onComplete: function () {
                $submenu.removeClass('visible');
                slyRender();
            }
        });
    }

    function menuDoExpand($submenu, $this, options) {
        $submenu.addClass('visible').height('');
        currentHeight = $submenu.outerHeight();
        var propsFrom = {
                opacity: .2,
                height: 0,
                top: -20
            },
            propsTo = {
                height: currentHeight,
                opacity: 1,
                top: 0
            };

        if (isxs()) {
            delete propsFrom['opacity'];
            delete propsFrom['top'];
            delete propsTo['opacity'];
            delete propsTo['top'];
        }

        TweenMax.set($submenu, {css: propsFrom});
        $this.addClass(options.submenuOpenedClass);
        TweenMax.to($submenu, options.submenuOpenDelay, {
            css: propsTo, ease: options.submenuOpenEasing, onComplete: function () {
                $submenu.attr('style', '');
                slyRender();
            }
        });
    }

    // Frame Transitions
    function initFrameTransitions() {
        var transitions = ['frame-fade', 'frame-right-in', 'frame-fade-only'];
        for (var i in transitions) {
            var transitionName = transitions[i];
            if (globalVars.$body.hasClass(transitionName)) {
                globalVars.$body.addClass(transitionName + '-init')
                setTimeout(function () {
                    globalVars.$body.removeClass(transitionName + ' ' + transitionName + '-init');
                }, 768);
                return;
            }
        }
    }

    var initFrameUI = function () {
        beforeUIReady();
        renderFrameLayout();
        UIReady();
        initFrameTransitions();
    };

    $(function () {
        initFrameUI();
    });
})(jQuery);